package com.itheima.reggie.service.impl;

import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    @Transactional
    public ShoppingCart add(ShoppingCart shoppingCart) {

        ShoppingCart dbCart = shoppingCartMapper.findByUidAnds(shoppingCart);
        if(dbCart != null){
            Integer number = dbCart.getNumber();
            dbCart.setNumber(number+1);
            shoppingCartMapper.updateNumberById(dbCart);
        }else{
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.save(shoppingCart);
            dbCart=shoppingCart;
        }
        return dbCart;
    }

    @Override
    public List<ShoppingCart> findByUid(Long userId) {
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.findByUid(userId);
        return shoppingCartList;
    }

    @Override
    public void clean(Long userId) {
        shoppingCartMapper.removeByUid(userId);
    }

    @Override
    public void sub(ShoppingCart shoppingCart) {
        Long dishId = shoppingCart.getDishId();
        Long setmealId = shoppingCart.getSetmealId();
        if(dishId !=null){
            ShoppingCart dbShoppingCart = shoppingCartMapper.findByDishId(dishId);
            Integer number = dbShoppingCart.getNumber();
            if(number>1){
                dbShoppingCart.setNumber(number-1);
                shoppingCartMapper.updateNumberById(dbShoppingCart);
            }else{
                shoppingCartMapper.deleteByDishId(dishId);
            }
        }else{
            ShoppingCart dbShoppingCart = shoppingCartMapper.findBySetmealId(setmealId);
            Integer number = dbShoppingCart.getNumber();
            if(number>1){
                dbShoppingCart.setNumber(number-1);
                shoppingCartMapper.updateNumberById(dbShoppingCart);
            }else{
                shoppingCartMapper.deleteBysetmealId(setmealId);
            }
        }
    }
}
